
package org.sopt.dev.ImgKnight.agent.NIO;

import java.util.concurrent.atomic.AtomicLong;

import org.apache.log4j.Logger;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.handler.codec.serialization.ObjectDecoder;
import org.jboss.netty.handler.codec.serialization.ObjectEncoder;

import org.sopt.dev.ImgKnight.agent.Agent;

@ChannelPipelineCoverage("all")
public class NioObjectStreamHandler extends SimpleChannelHandler {
	
	public static AtomicLong transferredMessages = new AtomicLong(0);
	
	private Agent agent = null;
	
	private Logger exceptionLogger = null;

	public NioObjectStreamHandler() {
		agent = Agent.getInstance();
		transferredMessages = new AtomicLong(0);
		exceptionLogger = Logger.getLogger("agent.exception");
	}
	
	@Override
	public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {
		e.getChannel().getPipeline().addFirst("encoder", new ObjectEncoder());
		e.getChannel().getPipeline().addFirst("decoder", new ObjectDecoder());
	}
	
	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
		agent.onConnectionEstablished(e.getChannel());
	}
	
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
		transferredMessages.incrementAndGet();
		agent.onRecvedObject(e.getMessage());
	}
	
	@Override
	public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
		agent.onConnectionClosed(e.getChannel());
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
		exceptionLogger.debug("Unexpected exception: "+e+": "+ e.getCause());
	}
	
	public static long getTransferredMessages() {
		return transferredMessages.get();
	}
	
}
